
import React from "react";
import { hashHistory } from 'react-router';
import InputBox from "../../common/InputBox"
import "./Limit.css";
import Bomb from './Bomb';
import Relay from "react-relay";

import CreateOrUpdateRole from "./mutation/CreateOrUpdateRole"
import GetRolesMutation from "./mutation/GetRolesMutation"
import GetPermissionMutation from "./mutation/GetPermissionMutation"

import ReactKey from "../../util/ReactKey"

import {Button} from 'fly';

import {_Table,_Input,_message} from 'ANT_DE';

const Table = _Table,
       Input = _Input,
      message = _message;

const columns = [{
    title: '功能名称',
    dataIndex: 'funName',
    width: 150,
    render: (value, row, index) => {
        const obj = {
            children: value,
            props: {},
        };
        if (index === 0) {
            obj.props.rowSpan = 3;
        }
        return obj;
    },
}, {
    title: '权限',
    dataIndex: 'perm',
    width: 150
}, {
    title: '权限名称',
    dataIndex: 'permName',
    render:(value,row,index)=>{
        const obj = {
            children: value,
            props: {},
        };
        if (index === 0 || index ===1 ||index === 2) {
            obj.props.cloSpan = 1;
        }
        return obj;
    }
}];
/*导出组件*/
export default class Limit extends React.Component{
    constructor(props){
        super(props);

        this.style={
            confirm:{
                width: '96px',
                height: '27px',
                lineHeight:"27px",
                backgroundColor: "#36b3b3",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius:"5px",
            },
            dutyName: {
                width: "293px",
                height: "30px",
                output:"none",
                borderColor:"#36b3b3",
                paddingLeft:6
            },
            dutyContext:{
                width: "293px",
                height: "146px",
                borderColor:"#36b3b3"
            },
            label: {
                float:"left",
                display:"inline-block",
                fontSize: "14px",
                vertical: "-align: -2px",
                width:"134px",
                height:"36px",
                lineHeight:"36px",
                paddingLeft:"30px",
                borderRight:"1px solid #ededed",
                borderBottom:"1px solid #ededed"
            },
            input: {
                width: "13px",
                height: "13px",
                verticalAlign:"-2px",
                borderRadius:"3px",
                marginRight:7
            },
        };
        this.listInfo=[
            {name:"企业设置",limit:{set_c:"",set_l:"",set_o:""},limit_des:{company:"设置企业信息，包括基本信息、支付账户、企业管理员",duty:"",order:""}},
            {name:"管理员",limit:{set_c:"",set_l:"",set_o:""},limit_des:{company:"设置企业信息，包括基本信息、支付账户、企业管理员",duty:"",order:""}},
            {name:"管理员",limit:{set_c:"",set_l:"",set_o:""},limit_des:{company:"设置企业信息，包括基本信息、支付账户、企业管理员",duty:"",order:""}},
        ]
        this.state={
            text:'',
            jobDes:"",
            permissionData:[],
            ischeckde:false,
            int: 1,
            key:''
        };
        this.enterpriseId = sessionStorage.getItem('enterpriseId');

        this.permissionId = sessionStorage.getItem('permissionId');
        this.enType = sessionStorage.getItem('entype');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.ischeck=[];
        this.onJobDesChange = this.onJobDesChange.bind(this);
        this.getPermission = this.getPermission.bind(this);
    }

    componentWillMount(){
        this.getPermission();
    }

    getPermission(){
        Relay.Store.commitUpdate(
            new GetPermissionMutation({
                enType:this.serviceType
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorcode = response.getAllPermission.getAllPermission.errorCode;
                    if(errorcode ==0){
                        this.setState({
                            permissionData:response.getAllPermission.getAllPermission.permissionModels
                        },()=>{
                            if(!this.props.params.id){
                                return
                            }
                            Relay.Store.commitUpdate(
                                new GetRolesMutation({
                                    rid:this.props.params.id
                                }),
                                {
                                    onFailure: () => {
                                    },
                                    onSuccess: (response) => {

                                        let errorcode = response.getRoles.getRoles.errorCode;

                                        if(errorcode ==0){
                                            let name = response.getRoles.getRoles.roles[0].name;
                                            let description = response.getRoles.getRoles.roles[0].description
                                            let pid = response.getRoles.getRoles.roles[0].pid;

                                            let arr = pid !== "" ? pid.split(',') : [];

                                            this.ischeck = arr;
                                            this.setState({
                                                text:description || ''
                                            });
                                            this.refs.dutyName.setState({
                                                text:name||''
                                            });
                                            if(pid === "0"){ return };
                                            this.ischeck.length !== 0 && this.ischeck.map((context,index)=>{
                                                this.refs[context+'index'].checked=true;
                                            });
                                        }
                                    }
                                }
                            )

                        })
                    }

                }
            }
        )
    }

    onclickbox(num,e){
        if(e.target.checked){
            this.ischeck.push(num);
        }else{
            this.ischeck.splice(this.ischeck.indexOf(num),1)
        }
    }

    /*新增职务*/
    backLimit(){
        hashHistory.push('/limit')
    }
    /*确定按钮*/
    backConfirm(){
        this.refs.handleOK.setState({
            handleOK:true
        })
    }

    onchange(e){
        this.setState({
            text:e.target.value
        });
    }
    //校验
    commitsurt(){
        let limitnum = [];

        this.ischeck.map((context,index)=>{
            if(context==1){
                limitnum.push(index)
            }
        });

        let description = this.state.text;
        let dutyName = this.refs.dutyName.state.text;
        let rid;
        //检验s
        if(dutyName.indexOf(" ") > -1 || dutyName.length == 0){
            message.error("请输入合法名称");
            return;
        }

        let arr = [] ;
        for( let i = 0; i<this.ischeck.length; i++ ){
            if(this.ischeck[i] !== undefined){
                arr.push(this.ischeck[i]);
            }
        }

        if(!this.props.params.id){
            rid =''
        }else{
            rid =this.props.params.id
        }


        Relay.Store.commitUpdate(
            new CreateOrUpdateRole({
                enid:this.enterpriseId,
                name:dutyName,
                pid: arr.join(","),
                description:description,
                rid:rid
            }),
            {
                onFailure: () => {
                    alert("网络出错");
                },
                onSuccess: (response) => {
                    const res = response.createOrUpdateRole.createOrUpdateRole;
                    if(res.errorCode === "0"){
                        let errorCode = response.createOrUpdateRole.createOrUpdateRole.errorCode;
                        if(errorCode==0){
                            hashHistory.push('/limit');
                        }
                    }else if(res.errorCode === "200003"){
                        message.error("角色已存在,请更换名称");
                    }else{
                        message.error(`${res.value}`)
                    }
                }
            }
        );
    }

    onJobDesChange(e){
        this.setState({
            text:e.target.value
        })
    }
    switchcontrol(is){
        this.setState({
            isswitch:is
        });
    }

    addList() {
        // 计算数据 整理格式 找出相同title块
        let obj = {}, test_obj = {}, arr_data = this.state.permissionData, arr = [], state;

        if (arr_data.length === 0) {return}

        // 查看种类
        for (let key in arr_data) {
            test_obj[arr_data[key].menuName] = 0;
        }
        const keys = Object.keys(test_obj);

        // 根据上面的几种类型，遍历排序
        for (let y = 0; y < keys.length; y++) {
            for (let key in arr_data) {
                const item = arr_data[key];
                if (item.menuName === keys[y]) {
                    arr.push(item);
                }
            }
        }

        // 对应类型出现的次数
        for (let i = 0; i < arr.length; i++) {
            if (obj[arr[i].menuName] !== undefined) {
                obj[arr[i].menuName]++;
            } else {
                obj[arr[i].menuName] = 1;
            }
        }

            // console.log(obj);
            // 根据menu排序
            return arr.map((ele, index) => {
                return (
                    <tr style={{height: "40px"}}>
                        {
                            (ele.menuName !== arr[index > 0 ? index - 1 : 0].menuName || index === 0) &&
                            <td rowSpan={obj[ele.menuName]}>
                                {/*<input type="checkbox"  style={{display:"block",float:"left",marginLeft:"15px"}} onClick={this.checkboxSelected.bind(this,index)}  />*/}
                                {ele.menuName}
                            </td>
                        }
                        <td>
                            <label className="checkbox_cover--label">
                                <span className="checkbox_cover--box"  style={{marginTop:5}}>
                                          <input type="checkbox" className="checkbox_cover--style"
                                                 onClick={this.onclickbox.bind(this, ele.pid)} ref={`${ele.pid}index`}/>
                                          <span data-checkbox="cover" style={{marginBottom:-3}}></span>
                                </span>
                                <span className="checkbox_cover--title">
                                      {ele.name}
                                </span>
                            </label>
                        </td>
                        <td>{ele.description}</td>
                    </tr>
                );
            });
        }

    render(){
        const {text} = this.state;
        return (
            <div className="limit clear">
                <div className="limit_duty_box">
                    <Button onClick={this.backLimit.bind(this)} type="primary" > 返回 </Button>
                    <div className="limit_edit_line"></div>
                    <div className="limit_edit_duty">
                        <div className="limit_edit_dn">
                            <span className="limit_edit_span"><span className="limit_edit_span limit_edit_red">*</span>职务名称</span>
                            <div className="limit_edit_position">
                                <InputBox  className="pro_overflow_inputSty" maxlength={50} style={this.style.dutyName} defaultvalute="请输入职务名称" ref={"dutyName"}/>
                            </div>
                        </div>

                        <p className="limit_edit_dc">
                            <span className="limit_edit_span">职务描述</span>
                            <textarea  className="limit_job_des pro_overflow_inputSty"  maxLength={200} cols="30" rows="10" value={text} placeholder="内容最多不得超过200个字"
                                onChange={(e)=>this.onJobDesChange(e)}
                            />
                        </p>
                    </div>
                    <table className="editlimit_table--list">
                        <thead>
                            <tr>
                                <th>功能名称</th>
                                <th>权限</th>
                                <th>权限描述</th>
                            </tr>
                        </thead>
                        <tbody className="editlimit_tab--body___item">
                            {
                                this.addList()
                            }
                        </tbody>
                    </table>
                    <div className="editlimit_ok">
                        <Button onClick={this.backConfirm.bind(this)}  type="primary" className="editlimit_ok" > 确定 </Button>
                    </div>
                </div>
                <Bomb ref={"handleOK"} commitsurt={this.commitsurt.bind(this)}/>
            </div>
        )
    }
}